# -*- coding:utf-8 -*-
from tkinter import *
from tkinter import ttk
from db import get_by_id
from PIL import Image, ImageTk
import os
import datetime
import tkinter.font


class MyDialog(Toplevel):
    def __init__(self, rf_id):
        super().__init__()
        self.minsize(1024, 768)
        self.rf_id = rf_id
        self.title(f'{rf_id}的领用记录')
        self.canvas = None  # 画布
        self.image_file = None  # 画布中的图片需要全局引用
        self.treeview = None
        self.time_length = StringVar()
        # 弹窗界面
        self.setup_UI()
        # self.grab_set()

    def setup_UI(self):
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()
        ww = 1024
        wh = 768
        x = (sw - ww) / 2
        y = (sh - wh) / 2
        self.geometry("%dx%d+%d+%d" % (ww, wh, x, y))
        # 第一行（两列）
        frame_top = ttk.Frame(self)
        frame_top["relief"] = "solid"
        self.canvas = Canvas(frame_top, bg='#c4c2c2', height=480, width=640)  # 绘制画布
        self.canvas.pack(side=TOP)
        ttk.Style().configure("redTime.TLabel", foreground="red")
        small_font = tkinter.font.Font(size=60)
        ttk.Label(frame_top, textvariable=self.time_length, style='redTime.TLabel', font=small_font).pack(side=TOP)
        frame_top.pack(side=TOP)

        frame_main = ttk.LabelFrame(self, text='领用记录')
        columns = ("编号", "名字", "操作", "时间", "图片地址")
        self.treeview = ttk.Treeview(frame_main, height=18, show="headings", columns=columns)  # 表格

        self.treeview.column("编号", width=100, anchor='center')  # 表示列,不显示
        self.treeview.column("名字", width=120, anchor='center')
        self.treeview.column("操作", width=60, anchor='center')
        self.treeview.column("时间", width=150, anchor='center')
        self.treeview.column("图片地址", width=700, anchor='center')

        self.treeview.heading("编号", text="编号")  # 显示表头
        self.treeview.heading("名字", text="名字")
        self.treeview.heading("操作", text="操作")
        self.treeview.heading("时间", text="时间")
        self.treeview.heading("图片地址", text="图片地址")

        for index, item in enumerate(get_by_id(self.rf_id)):
            self.treeview.insert('', 'end', values=(item[0], item[1], item[2], str(item[3]).split(" ")[0] + " " + str(item[4]).split(" ")[-1], item[5]))
            if index == 0:
                grant_time = datetime.datetime.strptime(str(item[3]).split(" ")[0] + " " + str(item[4]).split(" ")[-1], "%Y-%m-%d %H:%M:%S")
                delta = datetime.datetime.now() - grant_time
                # self.time_length.set(f'{delta.days}天,{delta.hour}小时,{delta.minute}分')
                self.time_length.set(f'{delta.days}天,{delta.seconds // 3600}小时,{delta.seconds % 3600 // 60}分')
                file_name = item[5]
                self.set_image(file_name)

        self.treeview.bind('<ButtonRelease-1>', self.show)
        self.treeview.pack(side=TOP, fill=BOTH, expand=YES)
        frame_main.pack(side=TOP, fill=BOTH, expand=YES)

    def show(self, event):
        if self.treeview.selection():
            item = self.treeview.selection()[0]
            item_text = self.treeview.item(item, "values")
            file_name = item_text[4]
            self.set_image(file_name)

    def set_image(self, file_name: str)-> None:
        file_name = file_name.strip()
        if file_name.startswith('\\'):
            file_name = file_name[1:]
        if os.path.exists(file_name):
            image = Image.open(file_name)
            out = image.resize((640, 480), Image.ANTIALIAS)
            self.image_file = ImageTk.PhotoImage(out)
            self.canvas.create_image(0, 0, anchor='nw', image=self.image_file)
        else:
            self.canvas.delete('all')
